package com.xxdh.service.impl;

import com.xxdh.domain.po.UserNoticeRelation;
import com.xxdh.exception.BusiException;
import com.xxdh.mapper.UserNoticeRelationMapper;
import com.xxdh.service.ICourseService;
import com.xxdh.service.IUserNoticeRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxdh.util.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 公告关系表 服务实现类
 * </p>
 *
 * @author zwg
 * @since 2024-10-19
 */
@Service
@RequiredArgsConstructor
public class UserNoticeRelationServiceImpl extends ServiceImpl<UserNoticeRelationMapper, UserNoticeRelation> implements IUserNoticeRelationService {
    private final ICourseService courseService;

    /**
     * 保存公告和老师、学生的关系
     * @param teacherId 老师id
     * @param noticeId 公告id
     */
    @Override
    public void saveNoticeRelationByTeacherIdAndNoticeId(Long teacherId, Long noticeId) {
        // 获取该老师的所有学生id
        List<Long> userIds = courseService.getStudentIdListByTeacherId(teacherId);
        // 添加老师id
        userIds.add(teacherId);
        // 批量添加公告和老师、学生的关系
        List<UserNoticeRelation> userNoticeRelations = userIds.stream()
                .map(userId -> {
                    UserNoticeRelation userNoticeRelation = UserNoticeRelation.builder()
                            .noticeId(noticeId).userId(userId).build();
                    if(userNoticeRelation.getUserId() == teacherId){
                        userNoticeRelation.setIsRead(1);
                    }
                    return userNoticeRelation;
                })
                .collect(Collectors.toList());
        saveBatch(userNoticeRelations);
    }

    /**
     * 删除公告和老师、学生的关系
     * @param noticeId 公告id
     */
    @Override
    public void removeByNoticeId(String noticeId) {
        boolean flag = lambdaUpdate().eq(UserNoticeRelation::getNoticeId, Long.valueOf(noticeId)).remove();
        if (!flag) {
            throw new BusiException("删除失败");
        }
    }

    /**
     * 获取公告和老师、学生的关系
     * @param useId 用户id
     * @return
     */
    @Override
    public List<UserNoticeRelation> getUserNoticeRelationListByUserId(Long useId) {
        // 查询公告和老师、学生的关系
        List<UserNoticeRelation> userNoticeRelations = lambdaQuery().eq(UserNoticeRelation::getUserId, useId).list();
        return userNoticeRelations;
    }

    @Override
    public void updateNoticeStatusByUserIdAndNoticeId(Long userId,Long noticeId) {
        boolean flag = lambdaUpdate().eq(UserNoticeRelation::getUserId, userId).eq(UserNoticeRelation::getNoticeId, noticeId).set(UserNoticeRelation::getIsRead,
                1).update();
        if (!flag) {
            throw new BusiException("更新失败");
        }
    }
}
